<template>
  <div
    v-loading.fullscreen.lock="loading"
    element-loading-text="pdf文件加载中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div style="width: 100%; position: absolute; z-index: 10; right: 30px; text-align: right;">
      <el-button
        type="primary"
        style="margin: 10px 0 20px 0;"
        @click.stop="downloadPdf"
      >下载到本地</el-button>
      <el-button
        type="primary"
        style="margin: 10px 0 20px 0; margin-left: 30px;"
        @click.stop="rotatePdf"
      >逆时针旋转90°</el-button>
    </div>

    <pdf v-for="i in numPages" ref="pdf" :key="i" :src="src" :page="i" :rotate="pageRotate" />
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import { toHttps } from '@/utils'
export default {
  name: 'Pdf',
  components: { pdf },
  data() {
    return {
      src: '',
      numPages: null, // 总页数
      loading: false,
      pageRotate: 0
    }
  },
  mounted() {
    this.getNumPages()
  },
  beforeDestroy() {
    localStorage.removeItem('pdfSrc')
  },
  methods: {
    // 计算pdf页码总数
    getNumPages() {
      if (localStorage.pdfSrc) {
        this.src = toHttps(localStorage.pdfSrc)
        this.loading = true
        const loadingTask = pdf.createLoadingTask(this.src)
        loadingTask.promise
          .then((pdf) => {
            this.numPages = pdf.numPages
            this.loading = false
          })
          .catch((err) => {
            console.error('pdf加载失败', err)
            this.loading = false
          })
      } else {
        this.$message.error('打开pdf失败，请重试')
        this.$router.go(-1)
      }
    },
    downloadPdf() {
      console.log('download')
      window.open(this.src, '_blank')
    },
    rotatePdf() {
      console.log('rotate')
      this.pageRotate -= 90
    }
  }
}
</script>

<style lang="scss" scoped>
p {
  padding: 0;
  margin: 0;
}
.tab-container {
  background: #fff;
  padding: 15px 15px 30px;
  .tabpane-container {
    padding-top: 20px;
  }
}
.list-item {
  overflow: hidden;
  font-size: 14px;
  a {
    float: left;
    padding-left: 15px;
  }
  a:hover {
    text-decoration: underline;
    color: #409eff;
  }
  span {
    float: right;
    color: #bbb;
    padding-right: 15px;
  }
}
.no-list {
  padding-left: 15px;
}
.info-pagination {
  margin-top: 30px;
  text-align: center;
}
.el-carousel__item {
  height: 500px;
}
.el-carousel__item img {
  width: 100%;
  height: 500px;
  object-fit: contain;
}
</style>
